{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "6b873f4f",
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "数据从网址 http://www.stat-nba.com/award/item5.html 获取并保存到 Sheet_0\n",
      "数据从网址 http://www.stat-nba.com/query.php?QueryType=all&AllType=season&AT=avg&order=1&crtcol=pts&PageNum=20 获取并保存到 Sheet_1\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import requests\n",
    "from bs4 import BeautifulSoup\n",
    "\n",
    "# 读取网址文件，获取所有网址\n",
    "with open(\"urls.txt\", \"r\") as file:\n",
    "    urls = file.readlines()\n",
    "\n",
    "# 遍历每个网址\n",
    "for index, url in enumerate(urls):\n",
    "    # 去除换行符\n",
    "    url = url.strip()\n",
    "    \n",
    "    # 获取HTML内容\n",
    "    r = requests.get(url)\n",
    "    html_content = r.content\n",
    "    \n",
    "    # 解析HTML内容，提取表格数据\n",
    "    soup = BeautifulSoup(html_content, 'html.parser')\n",
    "    table = soup.find('table')\n",
    "    table_rows = table.find_all('tr')\n",
    "    \n",
    "    # 读取表格数据到列表\n",
    "    data = []\n",
    "    for tr in table_rows:\n",
    "        td = tr.find_all('td')\n",
    "        row = [i.text.strip() for i in td]\n",
    "        if row:\n",
    "            data.append(row)\n",
    "    \n",
    "    # 将数据转换成DataFrame，并设置列名\n",
    "    df = pd.DataFrame(data)\n",
    "    \n",
    "    # 将DataFrame保存到Excel文件的不同sheet中\n",
    "    with pd.ExcelWriter(\"output.xlsx\", mode='a', engine='openpyxl') as writer:\n",
    "        df.to_excel(writer, sheet_name=f'Sheet_{index}', index=False)\n",
    "    \n",
    "    print(f\"数据从网址 {url} 获取并保存到 Sheet_{index}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "564a67ce",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d13f0445",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
